// pages/test/test.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    groups: [],
    // marathon_id: String, //id1
    // name: String, //id2
    // members: String,
    // captain: String,
    // detail: String
    images: [],
    auth: '0',
    dimen: [],
    marathon: {},
    // name: String,  //id
    // start_time: String,
    // stop_time: String,
    // address: String,
    // organizer: String,
    // participants: String,
    // detail: String,
    // votes_for_teacher: String,
    // weight_for_teacher: String,
    // votes_for_student: String,
    // dimensions_for_vote: String,
    // status: String //0：未开始 1: 报名  2：投票 3：投票截止 4: 二轮投票 5： 二轮投票截止 6：已结束
    // students: String
    vote: {},
    disabled: false,
    check_list: [],
    participation: 0,
    scroll: "_1",
    searchValue: '',
    showClearBtn: false
  },

  //输入内容时
  searchActiveChangeinput: function (e) {
    var that = this
    const val = e.detail.value;
    if (isNaN(parseInt(val))) {
      that.setData({
        searchValue: '',
        showClearBtn: false,
        scroll: "_1"
      })
    } else {
      var index = parseInt(val)
      if (index >= 1 && index <= that.data.groups.length) {
        that.setData({
          showClearBtn: true,
          scroll: "_" + index
        })
      } else if (index < 1) {
        that.setData({
          showClearBtn: true,
          scroll: "_1"
        })
      } else if (index > that.data.groups.length) {
        that.setData({
          showClearBtn: true,
          scroll: "_" + that.data.groups.length
        })
      }
    }
  },
  //点击清除搜索内容
  searchActiveChangeclear: function (e) {
    this.setData({
      showClearBtn: false,
      searchValue: ''
    })
  },

  checkboxChange: function (e) {
    var that = this
    console.log('checkbox发生change事件，携带value值为：', e.detail.value)
    var group_point = e.detail.value
    var group = e.currentTarget.dataset.group
    var group_index = e.currentTarget.dataset.group_index
    var vote_temp = that.data.vote
    var check_list_temp = that.data.check_list
    var vote_num = "0"
    var auth = that.data.auth

    if (auth == "1" || auth == "3") {
      vote_num = that.data.marathon.votes_for_student
    } else if (auth == "2") {
      vote_num = that.data.marathon.votes_for_teacher
    }

    var dimen = that.data.dimen

    console.log(
      "group_point", group_point,
      "group", group,
      "group_index", group_index,
      "vote_temp", vote_temp,
      "check_list_temp", check_list_temp,
      "vote_num", vote_num,
      "auth", auth,
      "dimen", dimen
    )
    for (var i = 0; i < dimen.length; i++) {
      if (!group_point.includes(dimen[i])) {

        check_list_temp[group_index][i] = 0

        if (vote_temp[dimen[i]].indexOf(group) != -1) {
          vote_temp[dimen[i]].splice(vote_temp[dimen[i]].indexOf(group), 1)
        }

      }
    }

    for (var i = 0; i < group_point.length; i++) {
      if (!vote_temp[group_point[i]].includes(group)) {
        console.log(vote_temp[group_point[i]], vote_temp[group_point[i]].length, vote_num, parseInt(vote_num))
        if (vote_temp[group_point[i]].length == parseInt(vote_num)) {
          wx.showModal({
            title: '哎呀～',
            content: group_point[i] + " 维度票数已用完～",
            success: function (res) {
              if (res.confirm) {
                console.log('用户点击确定')
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        } else {
          vote_temp[group_point[i]].push(group)
          console.log(group_index, " ", that.data.dimen.indexOf(group_point[i]), " ", group_point[i])
          check_list_temp[group_index][that.data.dimen.indexOf(group_point[i])] = 1
        }

      }
    }

    that.setData({
      vote: vote_temp,
      check_list: check_list_temp
    })

  },

  //马拉松报名
  signup: function () {
    var that = this
    wx.navigateTo({
      url: '../hackson_signup/hackson_signup?marathonId=' + that.data.marathon.name,
    })
  },

  //提交投票
  submit: function () {
    var that = this
    console.log(that.data.vote);

    wx.showModal({
      title: '警告⚠️',
      content: "您确定提交投票吗？提交完投票您将不能再进行投票！",
      cancelText: "继续投票",
      confirmText: "确定提交",
      success: function (res1) {
        if (res1.confirm) {
          console.log('用户点击确定')

          wx.showModal({
            title: '再一次确认⚠️',
            content: "您确定提交投票吗？提交完投票您将不能再进行投票！",
            cancelText: "继续投票",
            confirmText: "确定提交",
            success: function (res1) {
              if (res1.confirm) {
                console.log('用户点击确定')

                var id = ""
                var auth = that.data.auth
                if (auth == "1") {
                  id = getApp().globalData.user.studentNo
                } else if (auth == "2") {
                  id = getApp().globalData.user.teacherNo
                } else if (auth == "3") {
                  id = getApp().globalData.user.adminNo
                }

                var level = ""
                var status = that.data.marathon.status
                if (status == "2"){
                  level = "1"
                } else if (status == "4"){
                  level = "2"
                }

                //投票
                wx.request({
                  url: getApp().globalData.my_server + "/hackson/vote",
                  data: {
                    role: that.data.auth, // 1 student,  2 teacher, 3 admin, 4 donator
                    id: id,
                    marathon_id: that.data.marathon.name, //id1
                    vote: JSON.stringify(that.data.vote), //id2
                    level: level
                  },
                  method: "POST",
                  header: {
                    "Content-Type": "application/x-www-form-urlencoded"
                  },
                  success: function (res) {
                    console.log(res)
                    if (res.data.error_no == 2) {
                      wx.showModal({
                        title: '哎呀～',
                        content: res.data.error_msg,
                        success: function (res) {
                          if (res.confirm) {
                            console.log('用户点击确定')
                          } else if (res.cancel) {
                            console.log('用户点击取消')
                          }
                        }
                      })
                    } else if (res.data.error_no == 0) {
                      that.setData({
                        disabled: true
                      })
                      wx.removeStorage({
                        key: 'vote_data',
                        success: function (res) {
                          console.log(res.data)
                          wx.showModal({
                            title: '提示',
                            content: "投票成功！",
                            success: function (res) {
                              if (res.confirm) {
                                console.log('用户点击确定')
                              } else if (res.cancel) {
                                console.log('用户点击取消')
                              }
                            }
                          })
                        }
                      })
                    }
                  },
                  fail: function (res) {
                    wx.showModal({
                      title: '哎呀～',
                      content: '投票失败',
                      success: function (res) {
                        if (res.confirm) {
                          console.log('用户点击确定')
                        } else if (res.cancel) {
                          console.log('用户点击取消')
                        }
                      }
                    })
                    console.log("fail!", res)
                  },
                  complete: function (res) {

                  }
                })
              } else if (res1.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        } else if (res1.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  generateImages: function (num = 12) {
    const image_list = ["/images/shuta.png", "/images/hema.png", "/images/huanxiong.png", "/images/haiyaoyu.png", "/images/houzi.png", "/images/baitu.png", "/images/yanjingshe.png", "/images/she.png", "/images/hudie.png", "/images/pangxie.png", "/images/daishu.png", "/images/luotuo.png", "/images/tuoniao.png", "/images/hashiqi.png"]

    var images_temp = []
    for (var i = 0; i < num; i++) {
      var picture = Math.floor(Math.random() * 14)
      images_temp.push(image_list[picture])
    }
    console.log(images_temp)
    this.setData({
      images: images_temp
    })
  },

  change_state: function (e) {
    var that = this
    var flag = e.currentTarget.dataset.flag
    //马拉松的状态改变
    wx.request({
      url: getApp().globalData.my_server + "/hackson/set_marathon_status",
      data: {
        name: that.data.marathon.name,
        flag: flag,
        status: that.data.marathon.status
      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        console.log(res)
        wx.showModal({
          title: '提示',
          content: res.data.error_msg,
          success: function (res1) {
            if (res1.confirm) {
              console.log('用户点击确定')
              if (res.data.error_no == 0) {
                wx.navigateBack({
                  delta: 1
                })
              }
            } else if (res1.cancel) {
              console.log('用户点击取消')
              if (res.data.error_no == 0) {
                wx.navigateBack({
                  delta: 1
                })
              }
            }
          }
        })
      },
      fail: function (res) {
        wx.showModal({
          title: '哎呀～',
          content: '马拉松的状态改变失败',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
        console.log("fail!", res)
      },
      complete: function (res) {

      }
    })
  },

  toDetail: function (e) {
    var that = this
    var group = e.currentTarget.dataset.group
    var marathon = that.data.marathon.name
    var status = that.data.marathon.status
    var members = e.currentTarget.dataset.members
    console.log("aaaaaaaaaa"+members);

    var id = ""
    var auth = that.data.auth
    if (auth == "1") {
      id = getApp().globalData.user.studentNo
    } else if (auth == "2") {
      id = getApp().globalData.user.teacherNo
    } else if (auth == "3") {
      id = getApp().globalData.user.adminNo
    } else if (auth == "4") {
      id = getApp().globalData.user.donatorNo
    }

    //记录浏览轨迹
    wx.request({
      url: getApp().globalData.my_server + "/hackson/trace",
      data: {
        role: getApp().globalData.kind, // 1 student,  2 teacher, 3 admin, 4 donator
        id: id,
        marathon_id: marathon, //id1
        name: group, //id2
        time: new Date().toString()
      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        console.log(res)
        if (res.data.error_no != 0) {
          wx.showModal({
            title: '提示',
            content: res.data.error_msg,
            success: function (res) {
              if (res.confirm) {
                console.log('用户点击确定')
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        } else if (res.data.error_no == 0) {
          wx.navigateTo({
            url: '../hackson_group_detail/hackson_group_detail?marathon=' + marathon + "&group=" + group + "&students=" + members + "&status=" + status,
          })
        }
      },
      fail: function (res) {
        wx.showModal({
          title: '哎呀～',
          content: '记录浏览轨迹失败',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
        console.log("fail!", res)
      },
      complete: function (res) {

      }
    })
  },

  toResult: function () {
    var that = this
    wx.navigateTo({
      url: '../result/result?marathon=' + that.data.marathon.name + "&status=" + that.data.marathon.status,
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;

    console.log(options);
    console.log(that.data.groups);
    that.setData({
      auth: getApp().globalData.kind,
      marathon: JSON.parse(options.marathon),
      dimen: JSON.parse(options.marathon).dimensions_for_vote.split(",")
    })
    // that.generateImages()

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this

    if (!(that.data.marathon.status == "2" || that.data.marathon.status == "4")) {
      try {
        wx.clearStorageSync()
      } catch (e) {
        console.log(e)
        // Do something when catch error
      }
    }

    //请求当前马拉松的参赛项目列表
    wx.request({
      url: getApp().globalData.my_server + "/hackson/get_groups_by_marathon_id",
      data: {
        marathon_id: that.data.marathon.name,
        status: that.data.marathon.status
      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        console.log(res)
        if (res.data.error_no == 2) {
          wx.showModal({
            title: '哎呀～',
            content: res.data.error_msg,
            success: function (res) {
              if (res.confirm) {
                console.log('用户点击确定')
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        } else if (res.data.error_no == 0) {
          that.generateImages(res.data.marathons.length)

          that.setData({
            groups: res.data.marathons
          })

          try {
            var value = wx.getStorageSync('vote_data')
            console.log(value)
            if (value) {
              // Do something with return value
              that.setData({
                vote: value.vote,
                check_list: value.check_list
              })
            } else {

              var vote_temp = {}
              var dimen = that.data.dimen
              for (var i = 0; i < dimen.length; i++) {
                var key = dimen[i]
                vote_temp = Object.assign(vote_temp, { [key]: [] })
              }

              var groups = res.data.marathons
              var check_list_temp = []
              for (var i = 0; i < groups.length; i++) {
                var temp = Array(that.data.dimen.length).fill(0)
                console.log(temp)
                check_list_temp.push(temp)
              }
              console.log(groups.length, that.data.dimen.length, check_list_temp)

              that.setData({
                vote: vote_temp,
                check_list: check_list_temp,
              })
            }
          } catch (e) {
            console.log(e)
          }
        }
      },
      fail: function (res) {
        wx.showModal({
          title: '哎呀～',
          content: '请求当前马拉松的参赛项目列表失败',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
        console.log("fail!", res)
      },
      complete: function (res) {

      }
    })

    if (that.data.marathon.status == "2" || that.data.marathon.status == "4") {
      var id = ""
      var auth = that.data.auth
      if (auth == "1") {
        id = getApp().globalData.user.studentNo
      } else if (auth == "2") {
        id = getApp().globalData.user.teacherNo
      } else if (auth == "3") {
        id = getApp().globalData.user.adminNo
      }
      //检查是否投过票
      wx.request({
        url: getApp().globalData.my_server + "/hackson/check_voted",
        data: {
          role: that.data.auth, // 1 student,  2 teacher, 3 admin, 4 donator
          id: id,
          marathon_id: that.data.marathon.name, //id1
          status: that.data.marathon.status
        },
        method: "POST",
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        success: function (res) {
          console.log(res)
          if (res.data.error_no == 2) {
            that.setData({
              disabled: true
            })
            wx.showModal({
              title: '提示',
              content: res.data.error_msg,
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          } else if (res.data.error_no == 1) {
            that.setData({
              disabled: true
            })
          }
        },
        fail: function (res) {
          wx.showModal({
            title: '哎呀～',
            content: '检查是否投过票失败',
            success: function (res) {
              if (res.confirm) {
                console.log('用户点击确定')
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
          console.log("fail!", res)
        },
        complete: function (res) {

        }
      })
    }

    if (that.data.auth == "1") {
      //检查该学生是否参加此次活动
      wx.request({
        url: getApp().globalData.my_server + "/hackson/check_signed_for_student",
        data: {
          studentNo: getApp().globalData.user.studentNo,
          marathon_id: that.data.marathon.name, //id1
        },
        method: "POST",
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        success: function (res) {
          console.log(res)
          if (res.data.error_no != 0) {
            wx.showModal({
              title: '提示',
              content: res.data.error_msg,
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          } else if (res.data.error_no == 0) {
            that.setData({
              participation: 1
            })
          }
        },
        fail: function (res) {
          wx.showModal({
            title: '哎呀～',
            content: '检查该学生是否参加此次活动失败',
            success: function (res) {
              if (res.confirm) {
                console.log('用户点击确定')
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
          console.log("fail!", res)
        },
        complete: function (res) {

        }
      })
    } else if (that.data.auth == "2" || that.data.auth == "3") {
      that.setData({
        participation: 1
      })
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    var that = this
    try {
      console.log(that.data)
      wx.setStorageSync('vote_data', {
        vote: that.data.vote,
        check_list: that.data.check_list
      })
      console.log("saved")
    } catch (e) {
      console.log(e)
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var that = this
    try {
      console.log(that.data)
      wx.setStorageSync('vote_data', {
        vote: that.data.vote,
        check_list: that.data.check_list
      })
      console.log("saved")
    } catch (e) {
      console.log(e)
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})